// Example two processes comunicating via shared memory: 
// shm_server.c, shm_client.c
// http://www.cs.cf.ac.uk/Dave/C/node27.html

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>

#define SHMSZ 27 

void main(int argc, char* argv[]){
	char c;
	int shmid;
	key_t key;
	char *shm, *s;
	 
     // We'll name our shared memory segment "5678".
    key = 5678;
	// or use file as key: 
	// if ((key = ftok("hello.txt", 'R')) == -1){xxxx} /*Here the file must exist */ 
    // ftok  -  convert  a pathname and a project identifier to a System V IPC key

    // locate the segment
    if( (shmid=shmget(key,SHMSZ,0666)) == -1){
    	perror("shmget error");
    	exit(1);
    }

    // attach the segment to our data space
    shm = shmat(shmid, NULL, 0);
    if(shm == (char *)(-1)){
		perror("shmat");
		exit(1);
    }

    // now put some things into mem, for other process to read

    s = shm;
    for(s=shm; *s != '\0'; s++){
        putchar(*s);
    }
    putchar('\n');

    /*
     * Finally, change the first character of the 
     * segment to '*', indicating we have read 
     * the segment.
     */
    *shm='*';
    sleep(20);
    exit(0);
}